<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fileReader方法</title>
</head>
<body>
    <section>
        <label>请选择一个文件：</label>
        <input id="file" type="file" />
        <div>
            <button onclick="readAsDataUrl()">读取图像</button>
            <button onclick="readAsBinaryString()">读取二进制数据</button>
            <button onclick="readAsText()">读取文本文件</button>
            <button onclick="readDirectory()">读取目录</button>
        </div>
    </section>
    <output id="result"></output>
    <script>
        function readAsDataUrl () {
            const file = document.getElementById('file').files[0];
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
              const result = document.getElementById('result');
              result.innerHTML = `<img src="${this.result}" alt=""/>`
            };
        }

        function readAsBinaryString () {
            const file = document.getElementById('file').files[0];
            const reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = function (e) {
                const result = document.getElementById('result');
                result.innerHTML = this.result;
            };
        }
        
        function readAsText () {
            const file = document.getElementById('file').files[0];
            const reader = new FileReader();
            reader.readAsText(file);
            reader.onload = function (e) {
                const result = document.getElementById('result');
                result.innerHTML = this.result;
            };
        }

        function readDirectory () {
            //TODO 未生效
            window.webkitRequestFileSystem(PERSISTENT, 1024, function (fs) {
                console.log(fs);
                const reader = fs.root.createReader();
                const arr = [];
                const readEntries = function () {
                    reader.readEntries(function (results) {
                        if(!results.length){
                            listResults(arr);
                        }else{
                            arr.push(...results);
                            readEntries();
                        }
                    });
                };
                readEntries();
            });
        }

        function listResults (arr) {
            var type;
            arr.forEach(function (item) {
                if(item.isFile){
                    type = '文件：' + item.name;
                }else{
                    type = '目录：' + item.name;
                }
                document.getElementById('result').innerHTML += type + '<br/>';
            })
        }
    </script>
</body>
</html>